package com.coffee.attachment.excel;

import cn.hutool.core.util.StrUtil;
import com.coffee.core.CoffeeHeader;
import com.coffee.core.CoffeeResponse;
import com.coffee.core.CoffeeResponseEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author: songkui
 * @since: 2023/4/21 10:05
 */
@Slf4j
@RestController
@RequestMapping("/attach")
@AllArgsConstructor
public class ExcelEndpoint {

    private final MochaImportService mochaImportService;
    private final MochaExportService mochaExportService;


    /**
     * 异步 导出
     * @param excelQuery
     * @param request
     * @return
     */
    @PostMapping("/excel/export")
    public CoffeeResponse<String> exportExcel(@RequestBody MochaExportQuery excelQuery, HttpServletRequest request) {
        if (null == excelQuery || StrUtil.isEmpty(excelQuery.getExcelCode())){
            return CoffeeResponse.response(CoffeeResponseEnum.ParamInvalid);
        }
        CoffeeHeader.UserInfo userInfo = CoffeeHeader.getUserInfo(request);
        if (null == userInfo){
            return CoffeeResponse.response(CoffeeResponseEnum.LoginFailed);
        }
        mochaExportService.export(excelQuery, userInfo);
        return CoffeeResponse.response(CoffeeResponseEnum.Success);
    }


    /**
     * 异步导入
     * @param file
     * @param excelcode
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/excel/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public CoffeeResponse<String> importExcel(@RequestPart("file") MultipartFile file, @RequestParam("excelcode") String excelcode, HttpServletRequest request) throws Exception {
        if (null == file || file.isEmpty() || StrUtil.isEmpty(excelcode)){
            return CoffeeResponse.response(CoffeeResponseEnum.ParamInvalid);
        }


        String fileSuffix = Optional.ofNullable(file.getOriginalFilename()).map(f -> f.substring(f.lastIndexOf("."))).orElse("");
        if (!ExcelConstant.ImportExt.contains(fileSuffix)){
            return CoffeeResponse.response(ExcelResponseEnum.ExcelFileExteError);
        }

        CoffeeHeader.UserInfo userInfo = CoffeeHeader.getUserInfo(request);
        if (null == userInfo){
            return CoffeeResponse.response(CoffeeResponseEnum.LoginFailed);
        }
        mochaImportService.importExcel(excelcode, file, userInfo);
        return CoffeeResponse.response(CoffeeResponseEnum.Success);

    }


}
